package com.huangfu.easysardine.gate.service;

import com.huangfu.easysardine.common.vo.user.UserInfo;
import com.huangfu.easysardine.gate.biz.UserSecurity;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * User: huangfu.daohui
 * Date: 2017-8-14
 * Time: 13:45
 * Description：Spring Security用户身份认证，登录验证
 */
@Service
public class GateUserDetailsService implements UserDetailsService {
    @Autowired
    private UserSecurity userSecurity;

    /**
     * 根据用户输入的用户名，从数据库里面获取该用户的所有权限细信息（统称用户信息）
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isBlank(username)) {
            throw new UsernameNotFoundException("用户名为空");
        }

        //获取用户信息
        UserInfo info = userSecurity.getUserByUsername(username);
        Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
        return new org.springframework.security.core.userdetails.User(username, info.getPassword(),
                true, // 是否可用
                true, // 是否过期
                true, // 证书不过期为true
                true, // 账户未锁定为true
                authorities);
    }
}
